import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp , int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);
    }

    public void start(){
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            //从控制台读取请求, 发送给服务器.
            while (true){
                //1.从控制台读取请求
                String request = scanner.next();
                //2.将请求发给服务器
                //outputStream.write(request.getBytes());
                printWriter.println(request);
                //加上刷新缓冲区操作, 才是真正发送数据
                printWriter.flush();
                //3.读取服务器的响应
                String response = scannerNet.next();
                //4.打印响应
                System.out.println(response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
